import { Injectable, Inject } from '@nestjs/common';
import { Book } from './entities/book.entity';

import { DbService } from '../db/db.service';
import { BadRequestException } from '@nestjs/common';

function randomNum() {
  return Math.floor(Math.random() * 1000000);
}

@Injectable()
export class BookService {

  @Inject(DbService)
  dbService: DbService;

  async list() {
    const books: Book[] = await this.dbService.read();
    return books
  }

  async findById(id: number) {
    const books: Book[] = await this.dbService.read();
    const foundbook = books.find(item => item.id === id);
    if (!foundbook) {
      throw new BadRequestException('没有找到该书');
    }
    return foundbook;
  }
  async create(createBookDto: any) {
    const books: Book[] = await this.dbService.read();
    const foundbook = books.find(item => item.name === createBookDto.name);
    if (foundbook) {
      throw new BadRequestException('书名重复了');
    }
    const book = new Book();
    book.id = randomNum();
    book.name = createBookDto.name;
    book.author = createBookDto.author;
    book.description = createBookDto.description;
    book.cover = createBookDto.cover;
    books.push(book);
    await this.dbService.write(books);
    return book;
  }
  async update(updateBookDto: any) {
    const books: Book[] = await this.dbService.read();
    const foundbook = books.find(item => item.id === updateBookDto.id);
    if (!foundbook) {
      throw new BadRequestException('没有找到该书');
    }
    foundbook.name = updateBookDto.name;
    foundbook.author = updateBookDto.author;
    foundbook.description = updateBookDto.description;
    foundbook.cover = updateBookDto.cover;
    await this.dbService.write(books);
    return foundbook;
  }
  async delete(id: number) {
    const books: Book[] = await this.dbService.read();
    const foundbook = books.find(item => item.id === id);
    if (!foundbook) {
      throw new BadRequestException('没有找到该书');
    }
    const index = books.indexOf(foundbook);
    books.splice(index, 1);
    await this.dbService.write(books);
    return foundbook;
  }
}
